import { useEffect, useState } from "react"
import type { ModelProvider } from "@/app/api/model-providers/route"

export function useModelProviders() {
  const [providers, setProviders] = useState<ModelProvider[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    loadProviders()
  }, [])

  const loadProviders = async () => {
    try {
      setLoading(true)
      const response = await fetch("/api/model-providers")
      const result = await response.json()

      if (result.success) {
        // 只返回已启用的供应商
        const enabledProviders = (result.data || []).filter((p: ModelProvider) => p.enabled)
        setProviders(enabledProviders)
      } else {
        setError(result.error || "Failed to load providers")
      }
    } catch (err) {
      console.error("Error loading providers:", err)
      setError("Network error")
    } finally {
      setLoading(false)
    }
  }

  return {
    providers,
    loading,
    error,
    reload: loadProviders,
  }
}

// 将供应商转换为选项格式
export function providersToOptions(providers: ModelProvider[]) {
  return providers.map((p) => ({
    label: p.name,
    value: p.id.toLowerCase(),
  }))
}
